package net.xdclass.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import net.xdclass.common.enums.AddressStatusEnum;
import net.xdclass.common.enums.BizCodeEnum;
import net.xdclass.common.exception.BizException;
import net.xdclass.local.ThreadLocal;
import net.xdclass.user.mapper.AddressMapper;
import net.xdclass.user.model.AddressDO;
import net.xdclass.common.model.LoginUser;
import net.xdclass.user.model.vo.AddressVO;
import net.xdclass.user.request.AddressAddRequest;
import net.xdclass.user.service.AddressService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressMapper addressMapper;

    /**
     * 根据id删除指定收货地址
     *
     * @param id
     * @return
     */
    @Override
    public int deleteAddressById(Long id) {
        LoginUser loginUser = ThreadLocal.getLoginUser();
        QueryWrapper<AddressDO> wrapper = new QueryWrapper<AddressDO>()
                .eq("user_id", loginUser.getId())
                .eq("id", id);
        return addressMapper.delete(wrapper);
    }

    /**
     * 查询当前用户所有收货地址
     *
     * @return
     */
    @Override
    public List<AddressVO> selectUserAllAddress() {
        LoginUser loginUser = ThreadLocal.getLoginUser();
        QueryWrapper<AddressDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", loginUser.getId());
        List<AddressDO> dos = addressMapper.selectList(wrapper);
        return dos.stream().map(d -> {
            AddressVO v = new AddressVO();
            BeanUtils.copyProperties(d, v);
            return v;
        }).collect(Collectors.toList());
    }

    /**
     * 新增收货地址
     *
     * @param address
     * @return
     */
    @Override
    public int addAddress(AddressAddRequest address) {
        LoginUser loginUser = ThreadLocal.getLoginUser();
        AddressDO addressDO = new AddressDO();
        BeanUtils.copyProperties(address, addressDO);
        addressDO.setCreateTime(new Date());
        addressDO.setUserId(loginUser.getId());
        // 判断是否有默认收货地址[默认地址只能有一个]
        if (address.getDefaultStatus() == AddressStatusEnum.DEFAULT.getStatus()){
            // 查找
            QueryWrapper<AddressDO> wrapper = new QueryWrapper<>();
            wrapper.eq("default_status", AddressStatusEnum.DEFAULT.getStatus())
                    .eq("user_id", loginUser.getId());
            AddressDO add = addressMapper.selectOne(wrapper);
            if (add != null){
                // 修改为非默认收货地址
                // 多线程下update add会不会有并发安全问题：其他线程在这里修改了add的属性值，这里又set回去了？
                // 解决方案：new AddressDo，只set id和defaultstatus
//                add.setDefaultStatus(AddressStatusEnum.COMMON.getStatus());
                AddressDO update = new AddressDO();
                update.setId(add.getId());
                update.setDefaultStatus(AddressStatusEnum.COMMON.getStatus());
                addressMapper.updateById(update);
            }
        }

        int rows = addressMapper.insert(addressDO);
        log.info("新增收货地址成功, {}", addressDO);
        return rows;
    }

    /**
     * 根据id查询指定的收货地址
     *
     * @param id
     * @return
     */
    @Override
    public AddressVO selectAddressById(Long id) {
        LoginUser loginUser = ThreadLocal.getLoginUser();
        QueryWrapper<AddressDO> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", loginUser.getId())
                .eq("id", id);
        AddressDO addressDO = addressMapper.selectOne(wrapper);
        if (addressDO == null){
            return null;
        }
        AddressVO addressVO = new AddressVO();
        BeanUtils.copyProperties(addressDO, addressVO);
        return addressVO;
    }


}
